#include "shelf_generator.h"

#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iostream>

ShelfGenerator::ShelfGenerator()
{
    std::srand (std::time(0));
}

ShelfGenerator::ShelfGenerator(std::string config_file)
  : config_file_(config_file)
{
    std::srand (std::time(0));
}

bool ShelfGenerator::generate ()
{
  items_.clear ();
  items_.resize (REGIONS, std::vector<std::string>(NUMBERS, ""));


  std::ifstream fs;
  fs.open (config_file_.c_str (), std::ifstream::in);
  if (!fs.is_open ())
  {
    std::cout << "Cannot open configuration file" << std::endl;
    return false;
  }

  while (!fs.eof ())
  {
    std::string name;
    fs >> name;
    if (name.empty ())
      break;

    std::string region;
    int region_idx;
    fs >> region;
    assert(region.length () == 1);
    region_idx = region[0] - 'A';
    assert(region_idx >= 0 && region_idx < REGIONS);

    std::vector<int> number_idxs(0);


    int num, num_idx;
    fs >> num;
    num_idx = num - 1;
    assert(num_idx >= 0 && num_idx < NUMBERS);

    char opt;
    fs >> opt;
    assert(opt == ' '|| opt == '-');

    if (opt == '-')
    {
      int num2, num2_idx;
      fs	 >> num2;
      num2_idx = num2 - 1;
      assert(num2_idx >= 0 && num2_idx < NUMBERS);
      for (int i = num_idx; i <= num2_idx; i++)
        number_idxs.push_back (i);
    }

    int count;
    fs >> count;
    bool modified = true;
    while (modified)
    {
      modified = false;
      for (std::vector<int>::iterator it = number_idxs.begin (); it != number_idxs.end (); ++it)
      {
        if (!items_[region_idx][*it].empty())
        {
          number_idxs.erase (it);
          modified = true;
          break;
        }
      }
    }
    assert((unsigned)count <= number_idxs.size ());

    for (std::vector<int>::iterator it1 = number_idxs.begin (); it1 != number_idxs.end (); ++it1)
      for (std::vector<int>::iterator it2 = number_idxs.begin (); it2 != number_idxs.end (); ++it2)
        if (std::rand() % 2)
          std::swap(*it1, *it2);

    for (int i = 0; i < count; i++)
      items_[region_idx][number_idxs[i]] = name;
  }

  fs.close ();

  return true;
}
